package com.zyq.core.utils;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Data
public class OSSUtil {
    private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";
    private static final String ACCESSKEYID = "LTAI5tAAYmTCcSkYozTHsLxQ";
    private static final String ACCESSKEYSECRET = "44A7LRotCLM4kBKH5sw8Rz9slL6amW";
    private static final String BUCKETNAME = "second-group";
    private static final String PATH = "https://second-group.oss-cn-hangzhou.aliyuncs.com/";

    public static String upLoadImg(MultipartFile file) {


        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = UUID.randomUUID().toString() + file.getContentType().replace("image/", ".");

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);

        try {
            try {
                ossClient.putObject(BUCKETNAME, objectName, file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return PATH + objectName;
    }

}

